const app = getApp();
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: '37BBZ-IASRP-7VZDT-V6FJE-USUFE-OVFGR' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showAD: true,
    show_webview: false,
    show_adv: false,
    isBottom: 0,
    pageNum: 1,
    filter: [
      {},
      {},
      {
        title: '距离排序', is_show: false, list: [
          // { value: '默认排序', is_selected: true , type: 'no'},
          { value: '距离排序', is_selected: true, type: 'juli' },
          { value: '均价排序', is_selected: false, type: 'junjia'},
          { value: '热度排序', is_selected: false, type: 'hot' },
        ]
      }
    ],
    advList: [],
    advs: ['https://p1.meituan.net/deal/397fb38b86517d8f3ae8ce0280a3212d139631.jpg@750w_320h_1e_1c', 'https://p1.meituan.net/deal/397fb38b86517d8f3ae8ce0280a3212d139631.jpg@750w_320h_1e_1c'],
    new_list: ['佩姐老火锅', '昭通天麻火腿鸡', '李记串串香', '渝高宾馆1', '昭通天麻火腿鸡3'],
    shop_list: [],
    cates: [],
    searchChecked: false,
    cid: "",
    aid: "",
    fenxiangzhuan: {
      show: false,
      width: '118rpx;',
      height: '100rpx;',
      bottom: '212rpx;',
      top: '16rpx'
    },
    stype: 'juli'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if (options.showAD == 'no') {
      that.setData({
        showAD: false
      })
    }
    wx.showLoading({
      title: '加载中…',
    })
    let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
    this.setData({
      token: extConfig.appid
    })
    //请求后台获取分类
    wx.request({
      url: 'https://www.58zltc.com/api.php/Index/getCate?type=shop&id=' + options.id + '&token=' + this.data.token,
      success: res => {
        console.log(res);
        var new_filter = this.data.filter;
        new_filter[0] = res.data;
        this.setData({
          filter: new_filter
        })
      }
    })
    //请求后台获取地区
    wx.request({
      url: 'https://www.58zltc.com/api.php/Index/getAddressFilter?token=' + this.data.token,
      success: res => {
        var new_filter = this.data.filter;
        new_filter[1] = res.data;
        this.setData({
          filter: new_filter
        })
      }
    })
    wx.request({
      url: 'https://www.58zltc.com/api.php/Index/adv?type=shop&token=' + this.data.token,
      success: res => {
        this.setData({
          advList: res.data
        })
      }
    })
    wx.getLocation({
      success: function (res) {
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          complete: function (res) {
            console.log(res);
            that.setData({
              'address': res.result.address_component.district
            })
          }
        })
      }
    })
    wx.request({
      url: 'https://www.58zltc.com/api.php/Index/cate?type=shop&id=0&token=' + this.data.token,
      success: res => {
        const cates = res.data;
        var news = [];
        var item = [];
        cates.forEach(function (cate, index) {
          item.push(cate);
          console.log(item.length);
          if(index+1 === cates.length){
            news.push(item);
          }
          if (item.length == 10) {
            news.push(item);
            item = [];
          }
        })
        this.setData({
          cates: news
        })
        wx.hideLoading()
      }
    })
    // 广告
    if (that.data.showAD) {
      wx.request({
        url: 'https://www.58zltc.com/api.php/Index/getAdvShop?token=' + this.data.token + '&pos=2',
        success: res => {
          if (res.data) {
            that.setData({
              shop_advInfo: res.data,
              show_adv: true
            })
          }
        }
      })
    }
  },
  bindCall: function (e) {
    console.log(e);
    var tel = e.currentTarget.dataset.tel;
    console.log(tel);
    wx.makePhoneCall({
      phoneNumber: tel
    })
  },
  openSearch: function(){
    this.setData({
      searchChecked: true
    })
  },
  closeSearch: function () {
    this.setData({
      searchChecked: false
    })
  },

  setFilterPanel: function (e) {
    var findex = e.currentTarget.dataset.findex;
    var filter = this.data.filter;
    filter.forEach(function (value, key) {
      if (key == findex) {
        filter[key].is_show = !value.is_show;
      } else {
        filter[key].is_show = false;
      }
    })
    this.setData({
      filter: filter
    })
  },
  hideFilter: function () {
    var filter = this.data.filter;
    filter.forEach(function (value, key) {
      filter[key].is_show = false;
    })
    this.setData({
      filter: filter
    })
  },
  setCateIndex: function (e) {
    var cid = e.currentTarget.dataset.cid;
    var stype = e.currentTarget.dataset.type;
    this.setData({
      cid: cid,
      stype:stype
    })
    var keys = e.currentTarget.dataset.keys;
    var filter = this.data.filter;
    filter.forEach(function (value, key) {
      if (value.is_show) {
        value.list.forEach(function (vo, idx) {
          if (idx == keys) {
            filter[key].list[idx].is_selected = true;
          } else {
            filter[key].list[idx].is_selected = false;
          }
        })
      }
    })
    this.setData({
      filter: filter
    })
    //隐藏分类选项
    if (!this.data.filter[1].is_show) {
      //点击更新店铺
      this.getShopByCate();
      this.hideFilter();
    }
    if (this.data.filter[1].list[0].is_selected) {
      //点击更新店铺
      this.getShopByCate();
      this.hideFilter();
    }

  },
  setSubcateIndex: function (e) {
    var aid = e.currentTarget.dataset.aid;
    this.setData({
      aid: aid
    })
    var subindex = e.currentTarget.dataset.key;
    var filter = this.data.filter;
    filter.forEach(function (value, key) {
      if (value.is_show) {
        value.list.forEach(function (item, index) {
          if (item.is_selected) {
            item.sub_list.forEach(function (vo, idx) {
              if (idx == subindex) {
                filter[key].list[index].sub_list[idx].is_selected = true;
              } else {
                filter[key].list[index].sub_list[idx].is_selected = false;
              }
            })
          }
        })
      }
    })
    this.setData({
      filter: filter
    })
    //点击更新店铺
    this.getShopByCate();
    //隐藏分类选项
    this.hideFilter();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    app.confirmCommission()
  },
  //跳转到外卖店铺
  jumptoTakeout:function(e){
    var t = this
    console.log(e)
    wx.request({
      url: 'https://www.58zltc.com/api.php/Index/getTakeoutid?token=' + t.data.token + '&openid=' + e.currentTarget.dataset.openid,
      success: res => {
        getApp().sjid =res.data.id,
        wx.navigateTo({
          url: '/pages/index/takeout/info',
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      show_webview: false
    })
    var that =this;
    wx.getLocation({
      type: 'wgs84',
      complete: function (resq) {
        that.setData({
          laNum: resq.latitude,
          loNum: resq.longitude
        })
        wx.request({
          url: 'https://www.58zltc.com/api.php/Shop?token=' + that.data.token + '&pageNum=' + that.data.pageNum + '&la=' + that.data.laNum + '&lo=' + that.data.loNum + '&stype=' + that.data.stype,
          success: res => {
            that.setData({
              shop_list: res.data
            })
            wx.hideLoading()
          }
        })
      }
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onShow();
    this.onLoad({ showAD: 'no' });
    setTimeout(function () {
      wx.stopPullDownRefresh()
      wx.showToast({
        title: '已刷新',
      })
    }, 2000)
  },
  /**
 * 用户点击分类 地区 排序等检索条件
 */
  getShopByCate: function () {
    var t = this;
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: 'https://www.58zltc.com/api.php/Shop?cid=' + this.data.cid + '&aid=' + this.data.aid + '&stype=' + this.data.stype + '&token=' + this.data.token + '&pageNum=' + this.data.pageNum +'&la=' + this.data.laNum + '&lo=' + this.data.loNum ,
      success: function (res) {
        //处理返回数据
        t.setData({
          shop_list: res.data
        })
        //请求数据后延时关闭加载中
        if (res.data.length > 0) {
          setTimeout(function () {
            wx.hideLoading()
          }, 500)
        } else {
          wx.hideLoading()
        }
      },
      fail: function () {
        wx.hideLoading()
      }
    })
  },
  searchInputBind(e) {
    this.setData({
      searchInput: e.detail.value
    })
  },
  aa() {
    var url = "/pages/index/common/shopsearch?k=" + this.data.searchInput;
    console.log(url);
    wx.navigateTo({
      url: "/pages/index/common/shopsearch?k=" + this.data.searchInput,
    })
  },
  onReachBottom: function () {
    wx.showLoading({
      title: '加载中…',
    })
    var that = this
    var newPage = this.data.pageNum + 1;
    this.setData({
      pageNum: newPage
    })
    console.log(this.data.pageNum);
    wx.request({
      url: 'https://www.58zltc.com/api.php/Shop?cid=' + this.data.cid + '&aid=' + this.data.aid + '&stype=' + this.data.stype + '&token=' + this.data.token + '&pageNum=' + this.data.pageNum + '&la=' + this.data.laNum + '&lo=' + this.data.loNum ,
      success: res => {
        if (that.data.shop_list.length == res.data.length) {
          that.setData({
            isBottom: 1
          })
        }
        this.setData({
          shop_list: res.data
        })
        wx.hideLoading()
      }
    })
  },
  changeFXZ: function () {
    var that = this;
    var a = that.data.fenxiangzhuan
    a.show ? a.show = false : a.show = true
    that.setData({
      fenxiangzhuan: a
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    console.log('/pages/shop/shop' + '?fenxiang=' + app.globalData.openid + '&fWid=' + app.globalData.wid)
    return {
      title: '好店',
      path: '/pages/shop/shop' + '?fenxiang=' + app.globalData.openid + '&fWid=' + app.globalData.wid,
      success: function (res) {
        var a = that.data.fenxiangzhuan
        a.show = false
        that.setData({
          fenxiangzhuan: a
        })
        // 转发成功
        wx.showToast({
          title: '转发成功！',
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  jumpWeb: function (e) {
    console.log(e.currentTarget.dataset.type)
    let that = this
    var type_num = e.currentTarget.dataset.type
    var show_web = false
    if (type_num == 2) {
      show_web = true
    }
    this.setData({
      show_webview: show_web,
      show_adv: false
    })
  },
  onTabItemTap(item) {
    console.log(item)
    if (item.index == 1) {
      this.setData({
        show_webview: false
      })
    }
  },
  closeAdv: function () {
    this.setData({
      show_adv: false
    })
  }
})